package com.jrh.common.img;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片大小调节工具
 * 
 * @author jasen.hsu.cn@gmail.com 2012-7-21 下午8:59:43
 */
public class ImageResizer {

    private static final Logger log = LoggerFactory.getLogger(ImageResizer.class);

    /**
     * @param inputImgFile 源图文件路径
     * @param ouputImgFile 目标图文件路径
     * @param outputWidth 目标宽度
     * @param outputHeight 目标高度
     * @param proportion 是否等比
     * @return
     */
    public static boolean resize(String inputImgFile, String ouputImgFile, int outputWidth, int outputHeight,
                                 boolean proportion) {
        FileOutputStream out = null;
        try {
            // 获得源文件
            File inputFile = new File(inputImgFile);
            if (!inputFile.exists()) {
                log.error("img file is not exists");
                return false;
            }
            if (!ImageFileUtil.isImage(inputFile)) {
                log.error("not img file");
                return false;
            }
            Image img = ImageIO.read(inputFile);
            int newWidth;
            int newHeight;
            // 判断是否是等比缩放
            if (proportion == true) {
                double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.01;
                double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.01;
                double rate = rate1 > rate2 ? rate1 : rate2;
                newWidth = (int) (((double) img.getWidth(null)) / rate);
                newHeight = (int) (((double) img.getHeight(null)) / rate);
            } else {
                newWidth = outputWidth; // 输出的图片宽度
                newHeight = outputHeight; // 输出的图片高度
            }
            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
            out = new FileOutputStream(ouputImgFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            return true;
        } catch (Exception ex) {
            log.error("resize img error", ex);
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("close out", e);
                }
            }
        }
    }

}
